// pages/myOrderList/myOrderList.js
import * as API_Order from '../../api/order'
import * as API_Mall_Order from '../../api/mall/order'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    headshow: 0,
    tab_index: null,
    scrollLeft: 0,
    // listArray:[[],[],[],[]],
    listArray: [],
    params: {
      pageNum: 1,
      pageSize: 20,
      state: 'all'
    },
    paramsArr: [{
        pageNum: 1,
        pageSize: 20,
        state: 'all',
        finished: false,
        load: true
      },
      {
        pageNum: 1,
        pageSize: 20,
        state: 'wait_pay',
        finished: false,
        load: true
      },
      {
        pageNum: 1,
        pageSize: 20,
        state: 'wait_use',
        finished: false,
        load: true
      },
      {
        pageNum: 1,
        pageSize: 20,
        state: 'wait_comment',
        finished: false,
        load: true
      },
      {
        pageNum: 1,
        pageSize: 20,
        state: 'refund_success',
        finished: false,
        load: true
      },
    ],
    finished: false,
    origin: -1
  },
  detail(e) {
    wx.navigateTo({
      url: '../orderDetail/orderDetail?id=' + e.currentTarget.dataset.id,
    })
    // if(e.currentTarget.dataset.refund == 'no'){
    // }else{
    //   wx.navigateTo({
    //     url: '/pages/refundDetail/refundDetail?id='+e.currentTarget.dataset.id,
    //   })
    // }
  },
  goMallOrderDetail(e) {
    wx.navigateTo({
      url: '../mall/orderDetail/orderDetail?id=' + e.currentTarget.dataset.id,
    })
  },
  switchTab: function (e) {

    let current = e.currentTarget.dataset.tab_index;
    // //此处setData会触发tabIndexChange，所以不用主动调用tabIndexChangeHandle，避免多次执行
    this.setData({
      tab_index: current,
      // scrollhandle:false,
    });
    this.setData({
      'params.pageNum': 1,
      'params.state': e.currentTarget.dataset.state,
      listArray: []
    })
    this.getList()
  },
  tabIndexChange: function (e) {

    let current = e.detail.current;
    let item = this.data.paramsArr[current]
    item.pageNum = item.pageNum + 1
    this.tabIndexChangeHandle(current);
    this.setData({
      scrollhandle: true
    })
  },
  // tabIndexChangeHandle:function(current){
  //   console.info('tabIndexChangeHandle')
  //   this.setData({
  //     tab_index:current,
  //   });
  //   console.info('页签变化为'+current)
  //   let item = this.data.paramsArr[current]
  //   if(this.data.scrollhandle){
  //     //手动滑动才需要滑动到对应位置
  //     wx.createSelectorQuery()
  //     .select('.select_tab_view')
  //     .node()
  //     .exec((res) => {
  //       const scrollView = res[0].node;
  //       scrollView.scrollIntoView(".act")
  //     })
  //   }
  //   if(item.load){
  //     this.getList()
  //   }
  // },
  nextSwiper: function () {
    let len = this.data.serviceClassify.length;
    let current = this.data.tab_index;
    let next = current + 1;
    if (next > len - 1) {
      next = 0;
    }
    this.tabIndexChangeHandle(next);
  },
  showRightRecal: function () {
    //手动滑动才需要滑动到对应位置
    let that = this;
    wx.createSelectorQuery()
      .selectAll('.item')
      .boundingClientRect(function (rect) {
        let len = rect.length;
        if (len > 0) {
          //有元素
          let lastItem = rect[len - 1];
          let right = Number(lastItem.right);
          if (right > getApp().globalData.clientWidth) {
            that.setData({
              headshow: 1
            });
          }
        }
      }).exec();
  },
  scroll: function (e) {

    let deltaX = e.detail.deltaX;
    let scrollWidth = e.detail.scrollWidth;
    let scrollLeft = e.detail.scrollLeft + 80;
    let clientWidth = getApp().globalData.clientWidth;
    let rightX = scrollWidth - clientWidth;
    let opacity = 1
    if (rightX < scrollLeft) {

      opacity = (100 - (scrollLeft - rightX) * 3) / 100
    }
    this.setData({
      headshow: opacity
    })

  },
  viewImg(e) {
    let arr = [e.currentTarget.dataset.img]
    wx.previewImage({
      current: arr[0],
      urls: arr,
    })
  },

  handleProduct(item) {
    item.showComment = true
    item.showCode = false
    item.orderStateStr = item.orderState;
    switch (item.orderState) {
      case 'wait_use':
        item.showComment = false
        item.orderState = '待使用'
        if (item.aftersaleState == 'N') {
          item.showCode = true
        }
        break
      case 'wait_pay':
        item.orderState = '待付款'
        item.showComment = false
        break
      case 'used':
        if (item.writeOffNum > 0) {
          item.orderState = '待使用'
        } else {
          item.orderState = '已完成'
        }
        if (item.commentState == 'Y') {
          item.showComment = false
        }
        break
      case 'order_close':
        item.orderState = '订单关闭'
        item.showComment = false
        break
      case 'aftersale':
        item.orderState = '待售后'
        item.showComment = false
        break
      case 'received':
        item.orderState = '待评价'
        break
      case 'refund_apply':
        item.orderState = '申请退款'
        break
      case 'refund_success':
        item.orderState = '退款成功'
        break
    }
    console.log(item.orderState)
    // if (item.aftersaleState == 'Y') {
    if (item.orderState=='申请退款') {
      item.showComment = false
      item.orderState = '申请退款'
      switch (item.refundStatus) {
        case 'apply':
          item.orderState = '退款中'
          break
        case 'pass':
          item.orderState = '退款中'
          break
        case 'refunding':
          item.orderState = '退款中'
          break
        case 'refused':
          item.orderState = '拒绝退款'
          break
        case 'success':
          item.orderState = '退款成功'
          break
      }
    }
  },
  handleMall(item) {
    item.showComment = true
    item.showCode = false
    item.orderStateStr = '';
    item.showBtn = 'Y'
    switch (item.orderState) {
      case 'wait_ship':
        item.showComment = false
        item.orderStateStr = '待发货'
        break
      case 'shipped':
        item.orderStateStr = '待收货'
        item.showComment = false
        break
      case 'received':
        if (item.commentState == 'N') {
          item.orderStateStr = '待评价'
        }
        break
      case 'finished':
        item.orderStateStr = '已关闭'
        item.showComment = false
        item.showBtn = 'N'

        break
    }
    if (item.aftersaleState == "Y") {
      item.showComment = false
      item.orderStateStr = '售后订单'
    }
    if (item.payState == "N") {
      item.showComment = false
      if (item.orderState == 'finished') {
        item.orderStateStr = '已关闭'
        item.showComment = false
        item.showBtn = 'N'
      } else {
        item.orderStateStr = '待付款'
      }
    }
    if (item.commentState == "Y") {
      item.showComment = false
      item.orderStateStr = '已完成'
    }

  },
  cancelWaitOrder(e) {
    let that = this;
    let id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '是否确认取消订单？',
      success(res) {
        if (res.confirm) {
          API_Order.cancelOrder({orderId: id}).then(res => {
            setTimeout(() => {
              that.setData({
                'params.pageNum': 1,
                listArray: []
              })
              that.getList()
            }, 1500);
          })
          // that.cancel(id);
        }
      }
    })
  },
  cancelOrder(e) {
    let that = this;
    let id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '是否确认取消订单？',
      success(res) {
        if (res.confirm) {
          API_Mall_Order.cancelOrder(id).then(res => {
            setTimeout(() => {
              that.setData({
                'params.pageNum': 1,
                listArray: []
              })
              that.getList()
            }, 1500);
          })
          // that.cancel(id);
        }
      }
    })
  },
  toPayMall: function (e) {
    let that = this;
    let params = {
      orderId: e.currentTarget.dataset.id
    };
    API_Mall_Order.delayPay(params).then(res => {
      if (res.code == 200) {

        let payment = res.data;
        if (payment.status == "succeeded") {
          let expend = payment.expend;
          let pay_info = JSON.parse(expend.pay_info);

          wx.requestPayment({
            'timeStamp': pay_info.timeStamp,
            'nonceStr': pay_info.nonceStr,
            'package': pay_info.package,
            'signType': pay_info.signType,
            'paySign': pay_info.paySign,
            'success': function (res) {
              wx.showToast({
                title: '支付成功',
              })
            },
            'fail': function (res) {

            },
            'complete': function (res) {
              setTimeout(() => {
                that.setData({
                  'params.pageNum': 1,
                  listArray: []
                })
                that.getList()
              }, 1500);

            }
          })
        }
      } else {
        that.setData({
          payState: false
        });
        wx.showToast({
          title: res.msg,
          duration: 1500,
          success(res) {
            setTimeout(() => {
              that.setData({
                'params.pageNum': 1,
                listArray: []
              })
              that.getList()
            }, 1500);
          }
        })

      }

    })

  },
  getList() {
    API_Order.getList(this.data.params).then(res => {
      for (let item of res.data.rows) {
        if (item.type == 'O') {
          this.handleProduct(item)
        }
        if (item.type == 'M') {
          this.handleMall(item)
        }
      }
      let arr = []
      if (this.data.params.pageNum === 1) {
        arr = res.data.rows
      } else {
        arr = [...this.data.listArray, ...res.data.rows]
      }
      this.setData({
        listArray: arr,
        finished: res.data.lastPage
      })
    })
  },

  toPay: function (e) {
    let that = this;
    let orderId = e.currentTarget.dataset.id;
    let params = {
      orderId: orderId
    };
    API_Order.delayPay(params).then(res => {
      if (res.code == 200) {

        let payment = res.data;

        if (payment.status == "succeeded") {
          let expend = payment.expend;
          let pay_info = JSON.parse(expend.pay_info);

          wx.requestPayment({
            'timeStamp': pay_info.timeStamp,
            'nonceStr': pay_info.nonceStr,
            'package': pay_info.package,
            'signType': pay_info.signType,
            'paySign': pay_info.paySign,
            'success': function (res) {
              wx.showToast({
                title: '支付成功',
              })

              that.setData({
                tab_index: 2,
                listArray: []
              })
              that.setData({
                'params.pageNum': 1,
                'params.state': 'wait_use',
              })
              that.getList()

            },
            'fail': function (res) {

            },
            'complete': function (res) {

            }
          })
        }


      } else {
        wx.showToast({
          title: res.msg
        })
      }

    })

  },
  flush() {
    this.setData({
      listArray: [],
      'params.pageNum': 1
    })
    this.getList()
  },
  goComment(e) {
    wx.navigateTo({
      url: '/pages/commentEdit/commentEdit?orderId=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let globalData = getApp().globalData;
    let windowHeight = globalData.windowHeight;
    let navHeadHeightpx = globalData.navHeadHeightpx;
    this.setData({
      navHeadHeightpx: navHeadHeightpx,
      windowHeight: windowHeight
    });
    this.setData({
      tab_index: options.tabIndex
    })
    console.log(options)
    if(options.orgin) {
      this.setData({
        origin: options.orgin,
        url: '/pages/UCenter/index/index'
      })
      console.log(this.data.origin)
      console.log(this.data.url)
    }

    let state = options.state;
    this.setData({
      'params.state': state
    })
    if ("refund_success" == state) {
      this.setData({
        scrollLeft: 100
      })
    }
    // getApp().https.ajax({
    //   method: 'get',
    //   url: '/shape/getHandShapeList'
    // }).then(res => {
    //   console.log(res);
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //  this.showRightRecal();
    this.getList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let item = this.data.paramsArr[this.data.tab_index]
    if (this.data.finished) {
      return
    }
    var page = this.data.params.pageNum + 1
    this.setData({
      'params.pageNum': page
    })
    this.getList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})